package cn.rxmind.dlog.common.sender.db;

import cn.rxmind.dlog.common.DLogData;
import cn.rxmind.dlog.common.DLogDataSender;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import java.util.Iterator;
import java.util.List;


/**
 *
 * @description 这里了抽象出使用DB写出数据的Sender，需要组合数据源和sql模板
 *
 * @author renxin
 * @email renxinzhiliangzhi@163.com
 * @date 2020/7/10 2:36 下午
 */
@Slf4j
public class DBDLogDataSender implements DLogDataSender {

    private DataSource dataSource;

    private DLogSqlProvider sqlProvider;

    public DBDLogDataSender(DataSource dataSource, DLogSqlProvider sqlProvider) {
        this.dataSource = dataSource;
        this.sqlProvider = sqlProvider;
    }

    @Override
    public void sender(List<DLogData> dLogDataList) {

        String insertSQL = sqlProvider.getInsertSQL(dLogDataList);
        // 获取连接
        try (Connection connection = dataSource.getConnection();PreparedStatement pst = connection.prepareStatement(insertSQL);){

            int index = 0;
            for (DLogData dLogData : dLogDataList) {
                Iterator<String> iterator = sqlProvider.getColumnNames().iterator();
                while(iterator.hasNext()){
                    pst.setObject(++index,sqlProvider.mappingValue(iterator.next(),dLogData));
                }
            }
            pst.executeUpdate();
        } catch (SQLException e) {
            log.error("get DB Connection Error!",e);
            return;
        }

    }
}
